package com.eryos.test.springsecurity.server;

/**
 * Project :  SpringSecuritySimple
 * Author :   Olivier Combe
 * URL :      http://eryos-tech.blogspot.com/
 *
 * Copyright (C) 2011 - Olivier Combe 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */

import java.util.Enumeration;

import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import com.eryos.test.springsecurity.client.service.GreetingService;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
GreetingService {

	
	public String getUsername(){
		try {
			SecurityContext context = SecurityContextHolder.getContext();
			return context.getAuthentication().getName();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	
	public String greetServer(String input) {

		String serverInfo = getServletContext().getServerInfo();
		String userAgent = getThreadLocalRequest().getHeader("User-Agent");		

		return "Hello, " + input + "!<br><br>I am running " + serverInfo
		+ ".<br><br>It looks like you are using:<br>" + userAgent;
	}

	
	private void showSessionInformations(){
		try {
			System.out.println("Attributes : ");
			Enumeration enum1 = this.getThreadLocalRequest().getAttributeNames();
			while ( enum1.hasMoreElements() )
				System.out.println("     "+enum1.nextElement()+" : "+this.getThreadLocalRequest().getAttribute(enum1.nextElement().toString()));
			

			System.out.println("Parameters :");
			Enumeration enum2 = this.getThreadLocalRequest().getParameterNames();
			while ( enum2.hasMoreElements() )
				System.out.println("     "+enum2.nextElement()+" : "+this.getThreadLocalRequest().getParameter(enum2.nextElement().toString()));
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		try {
			SecurityContext context = SecurityContextHolder.getContext();
			System.out.println("Principal   : "+context.getAuthentication().getPrincipal());
			System.out.println("Name 		: "+context.getAuthentication().getName());
			System.out.println("Credentials : "+context.getAuthentication().getCredentials());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
